﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Miao
{
    class GameObjectPool
    {
        /// <summary>
        /// 默认的对象池大小
        /// </summary>
        public static int DefaultCapacity = 5;

        /// <summary>
        /// 缓存中的Stack
        /// </summary>
        private Stack<GameObject> _gameObjectStack;
        private Transform _root;
        private string _name;
        private GameObject _prefab;
        //private Type[] components;
        public GameObjectPool(GameObject prefab)
        {
            _root = new GameObject(prefab.name + "Pool").transform;
            _gameObjectStack = new Stack<GameObject>(DefaultCapacity);
            _prefab = prefab;
            for (int i = 0; i < DefaultCapacity; i++)
            {
                GameObject gameObject = GameObject.Instantiate(_prefab, this._root);
                gameObject.name = _prefab.name;
                gameObject.SetActive(false);
                _gameObjectStack.Push(gameObject);
            }
        }

        public GameObjectPool(params Type[] components)
        {
            _root = new GameObject(components[0].Name + "Pool").transform;
            //this.components = components;
            _gameObjectStack = new Stack<GameObject>(DefaultCapacity);
            _prefab = new GameObject(components[0].Name, components);
            for (int i = 0; i < DefaultCapacity; i++)
            {
                GameObject gameObject = GameObject.Instantiate(_prefab, this._root);
                gameObject.SetActive(false);
                _gameObjectStack.Push(gameObject);
            }
        }
        public GameObject Spawn(Transform parent)
        {
            if (_gameObjectStack.Count != 0)
            {
                GameObject gameObject = _gameObjectStack.Pop();
                gameObject.SetActive(true);
                gameObject.transform.SetParent(parent, false);
                return gameObject;
            }
            else
            {
                GameObject gameObject = GameObject.Instantiate(_prefab);
                gameObject.name = _prefab.name;
                //GameObject gameObject = new GameObject(components[0].Name, components);
                gameObject.SetActive(true);
                return gameObject;
            }
        }

        public void Despawn(GameObject gameObject)
        {
            gameObject.transform.SetParent(_root,false);
            gameObject.SetActive(false);
            _gameObjectStack.Push(gameObject);
        }
    }
}

